<?php

namespace app\api\controller;

use app\admin\model\Page;
use app\admin\model\Product;
use app\admin\model\Zhanlan;
use Throwable;
use think\Response;
use app\common\controller\Frontend;
use app\common\facade\Token;
use app\common\library\Upload;
use ba\Random;

class App extends Frontend
{
    protected array $noNeedLogin = ['artistList', 'artistDetail', 'activityList','activityDetail','storeList','storeDetail','exhibitionList'
    ,'exhibitionDetail', 'categoryList','productList','productDetail', 'adList','pageDetail','feedback','wxlogin','faqList',
        'shuffleProductOrder'];

    protected array $noNeedPermission = [];

    protected object $artistModel;
    protected object $activityModel;
    protected object $storeModel;
    protected object $exhibitionModel;
    protected object $protypeModel;
    protected object $productModel;
    protected object $adModel;

    // 微信小程序的 appid 和 secret（需替换为你的实际信息）
    private $appid = 'wx55e01b42dd86bcca';
    private $secret = '0b9c5d5603fe64ec2aeeb9ecdfeadede';

    public function initialize(): void
    {
        parent::initialize();
        $this->artistModel = new \app\admin\model\Artist();
        $this->activityModel = new \app\admin\model\Huodong();
        $this->storeModel = new \app\admin\model\Mendian();
        $this->exhibitionModel = new \app\admin\model\Zhanlan();
        $this->protypeModel = new \app\admin\model\Protype();
        $this->productModel = new \app\admin\model\Product();
        $this->adModel = new \app\admin\model\Ad();
    }

    /**
     * 打乱产品的排序
     */
    public function shuffleProductOrder(): void
    {
        $list = $this->productModel->select()->toArray();
        foreach ($list as $item) {
            $newWeigh = rand(1, 10000);
            $this->productModel->where('id', $item['id'])->update(['weigh' => $newWeigh]);
        }
    }

    /**
     * 获取艺术家列表信息
     * @throws Throwable
     */
    public function artistList(): void
    {      
        $list = $this->artistModel->select()->toArray();
        $this->success('获取成功', $list,1, 'json');
    }

    /**
     * 艺术家详细信息
     * @throws Throwable
     */
    public function artistDetail(int $id): void
    {
        $detail = $this->artistModel->find($id);
        if (!$detail) {
            $this->error('艺术家不存在');
        }
        $this->success('获取成功', $detail, 1, 'json');
    }

    /**
     * 获取 活动 列表信息
     * @throws Throwable
     */
    public function activityList(): void
    {
        $list = $this->activityModel->select()->toArray();
        $this->success('获取成功', $list, 1, 'json');
    }

    /**
     * 获取 活动 详细信息
     * @throws Throwable
     */
    public function activityDetail(int $id): void
    {
        $detail = $this->activityModel->find($id);
        if (!$detail) {
            $this->error('活动不存在');
        }
        $this->success('获取成功', $detail, 1, 'json');
    }

    /**
     * 获取 门店 列表信息
     * @throws Throwable
     */
    public function storeList(): void
    {
        $list = $this->storeModel->select()->toArray();
        $this->success('获取成功', $list, 1, 'json');
    }
    /**
     * 获取 门店 详细信息
     * @throws Throwable
     */
    public function storeDetail(int $id): void
    {
        $detail = $this->storeModel->find($id);
        if (!$detail) {
            $this->error('门店不存在');
        }
        $this->success('获取成功', $detail, 1, 'json');
    }

    /**
     * 获取展览的列表信息
     * @throws Throwable
     */
    public function exhibitionList(): void
    {
        $list = Zhanlan::with('artist')->where('isshow',1)->select()->toArray();
        
        $this->success('获取成功', $list, 1, 'json');
    }
    /**
     * 获取展览的详细信息
     * @throws Throwable
     */
    public function exhibitionDetail(int $id): void
    {
        $detail = Zhanlan::with('artist')->find($id);
        if (!$detail) {
            $this->error('展览不存在');
        }
        $this->success('获取成功', $detail, 1, 'json');
    }

    /**
     * 获取产品分类的列表信息
     * @throws Throwable
     */
    public function categoryList(): void
    {
        $list = $this->protypeModel->select()->toArray();
        $this->success('获取成功', $list, 1, 'json');
    }

    /**
     * 获取产品列表信息 带分页
     * @throws Throwable
     */
    public function productList(int $typeid = 0,int $page = 1, int $pageSize = 10,string $keyword = ''): void
    {
        $where = [];
        $where['isshows'] = 1; //只显示上架的
        if($typeid==-1){   //推荐模式
            $where['recom'] = 1;
        }
        if ($typeid == -2) {   //首页推荐模式
            $where['indexrecom'] = 1;
        }
        if($typeid > 0){  //分类模式
           
            $where[] = ['protype_id', 'find in set', $typeid];
          
        }
        if ($typeid == -3) {  //热门搜索
            $where['hotsearch'] = 1;
        }
        if($keyword){
            $where[] = ['title', 'like', '%'.$keyword.'%'];
        }
        $list = $this->productModel->where($where)->order('weigh desc,id desc')->page($page, $pageSize)->select()->toArray();
        $this->success('获取成功', $list, 1, 'json');
    }
    /**
     * 获取产品详细信息
     * @throws Throwable
     */
    public function productDetail(int $id): void
    {
        $detail = Product::with('artist')->find($id);
        if (!$detail) {
            $this->error('产品不存在');
        }
        $this->success('获取成功', $detail, 1, 'json');
    }
    /**
     * 获取广告列表信息
     * @throws Throwable
     */
    public function adList(string $weizhi = ''): void
    {
        $where = [];
        if($weizhi){
            $where['weizhi'] = $weizhi;
        }
        $list = $this->adModel->where($where)->order('weigh desc,id desc')->select()->toArray();
        foreach($list as &$item){
            if($item['type']=='product'){
                $item['product'] = Product::find($item['conid']);
                $item['appurl'] = '/pages/product/info?id='.$item['conid'];
            }
            if($item['type']== 'artist'){
                $item['appurl'] = '/pages/index/gjinfo?id='.$item['conid'];
            }
            if($item['type']== 'zhanlan'){
                $item['appurl'] = '/pages/zhanlanview/index?id='.$item['conid'];
            }
            if($item['type']== 'huodong'){
                $item['appurl'] = '/pages/index/hdinfo?id='.$item['conid'];
            }
            if ($item['type'] == 'page') {
                $item['appurl'] = '/pages/page/index?id=' . $item['conid'];
            }
            if ($item['type'] == 'mendian') {
                $item['appurl'] = '/pages/index/map?id=' . $item['conid'];
            }
        }
        $this->success('获取成功', $list, 1, 'json');
    }
    /**
     * 获取单页面详细信息
     * @throws Throwable
     */
    public function pageDetail(int $id): void
    {
        $detail = Page::find($id);
        if (!$detail) {
            $this->error('页面不存在');
        }
        $this->success('获取成功', $detail, 1, 'json');
    }

    /**
     * 记录意见反馈
     * @throws Throwable
     */
    public function feedback(): void
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $feedbackModel = new \app\admin\model\Feedback();
            $res = $feedbackModel->save($params);
            if ($res === false) {
                $this->error('提交失败');    
            }
            $this->success('提交成功');
        }
    }
    /**
     * 微信登录 - 根据 code 获取用户信息
     * @throws Throwable
     */
    public function wxlogin(string $code = ''): void
    {
        if (!$code) {
            $this->error('参数错误');
        }
        //第一步：用 code 换取 openid 和 session_key
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->secret}&js_code={$code}&grant_type=authorization_code";
        $response = file_get_contents($url);
        $data = json_decode($response, true);
        if (isset($data['errcode'])) {
            $this->error('登录失败，' . $data['errmsg']);
        }
        // 第二步：根据 openid 和 session_key 进行登录或注册
        $code = $data['code'] ?? '';
        $openid = $data['openid'] ?? '';
        $session_key = $data['session_key'] ?? '';
        if (!$openid || !$session_key) {
            $this->error('登录失败，获取用户信息失败');
        }
        
        $userModel = new \app\admin\model\User();
        //根据openid查询用户是否存在，存在则登录，不存在则注册
        $user = $userModel->where('openid', $openid)->find();
        if ($user) {
            $userModel->where('openid', $openid)->update([
                'session_key' => $session_key
            ]);
           
        }else{
            //注册用户
            $user = $userModel->create([
                'group_id'=>1,
                'nickname' => '微信用户',
                'username' => 'wx_' . time(),
                'openid' => $openid,
                'status' => 'enable',
                'session_key' => $session_key,
                'createtime' => time()
            ]);
            if (!$user) {
                $this->error('登录失败，用户注册失败');
            }
            $user = $userModel->find($user->id);
        }

        unset($user->session_key);
    
        $token = Random::uuid();
        Token::set($token, 'user', $user->id, 86400);

        $this->success('登录成功', ['token' => $token, 'userInfo' => $user], 1, 'json');

    }
    /**
     * 设置用户头像和基本信息
     * @throws Throwable
     */
    public function setUserInfo(): void
    {
        if ($this->request->isPost()) {
            $params = $this->request->post(['avatar', 'nickname', 'gender', 'birthday', 'mobile', 'email']);
            $params['gender'] = $params['gender']=='男'?1:2;
            $userModel = new \app\admin\model\User();
            $res = $userModel->where('id', $this->auth->id)->update($params);
            if ($res === false) {
                $this->error('设置失败');
            }
            $this->success('设置成功');
        }
    }
    /**
     * 获取用户的基本信息
     */
    public function getUserInfo(): void
    {
        $userModel = new \app\admin\model\User();
        $user = $userModel->find($this->auth->id);
        if (!$user) {
            $this->error('用户不存在');
        }
        unset($user->session_key);
        if($user->gender==1){
            $user->gender = '男';
        }else{
            $user->gender = '女';
        }
        $this->success('获取成功', $user, 1, 'json');
    }
    /**
     * 解密微信手机号（后端处理）
     * @throws Throwable
     */
    public function decryptPhone(): void
    {
        
        if ($this->request->isPost()) {
            $encryptedData = $this->request->post('encryptedData', '');
            $iv = $this->request->post('iv', '');
            if (!$encryptedData || !$iv) {
                $this->error('参数错误');            
            }
            $userModel = new \app\admin\model\User();
            $userInfo = $userModel->find($this->auth->id);

            // 解码
            $sessionKey = base64_decode($userInfo->session_key);
            $encryptedData = base64_decode($encryptedData);
            $iv = base64_decode($iv);

            // AES-128-CBC 解密
            $decrypted = openssl_decrypt(
                $encryptedData,
                'AES-128-CBC',
                $sessionKey,
                OPENSSL_RAW_DATA,
                $iv
            );

            if (!$decrypted) {
                $this->error('解密失败');
            }

            $data = json_decode($decrypted, true);

            // 验证数据有效性（校验 appid）
            if ($data['watermark']['appid'] != $this->appid) {
                $this->error('数据校验失败');
            }

            $result = [
               
                    'phoneNumber' => $data['phoneNumber'], // 手机号
                    'purePhoneNumber' => $data['purePhoneNumber'], // 不带国家码的手机号
                    'countryCode' => $data['countryCode'] // 国家码（如 86）
               
            ];
            $this->success('获取成功', $result, 1, 'json');
        }
    }
    /**
     * 添加或取消收藏
     * @throws Throwable
     */
    public function toggleCollect(int $conid = 0): void
    {
        if (!$conid) {
            $this->error('参数错误');
        }
        $collectModel = new \app\admin\model\Collect();
        $res = $collectModel->where('user_id', $this->auth->id)->where('product_id', $conid)->find();
        if ($res) {
            //已收藏，取消收藏
            $collectModel->where('id', $res->id)->delete();
        } else {
            //未收藏，添加收藏
            $collectModel->create([
                'user_id' => $this->auth->id,
                'product_id' => $conid,
                'createtime' => time()
            ]);
        }
      
        $this->success('操作成功');
    }
    /**
     * 查询某一个产品是否有收藏
     */
    public function hasCollect(int $conid = 0): void
    {
        if (!$conid) {
            $this->error('参数错误');
        }
        $collectModel = new \app\admin\model\Collect();
        $res = $collectModel->where('user_id', $this->auth->id)->where('product_id', $conid)->find();
        if ($res) {
            $this->success('已收藏');
        } else {
            $this->error('未收藏');
        }
    }
    /**
     * 增加足迹记录
     */
    public function addFootprint(int $productId = 0): void
    {
        if (!$productId) {
            $this->error('参数错误');
        }
        $footprintModel = new \app\admin\model\Footprint();
        //查询上一条记录是否跟当前记录相同
        $lastRecord = $footprintModel->where('user_id', $this->auth->id)->order('create_time', 'desc')->find();
        if ($lastRecord && $lastRecord->product_id == $productId) {
            $this->success('足迹记录成功');
        }
        //添加新记录
        $footprintModel->create([
            'user_id' => $this->auth->id,
            'product_id' => $productId,
            'create_time' => time()
        ]);
        $this->success('足迹记录成功');
    }
    /**
     * 获取收藏的列表 加 分页
     * throws Throwable
     */
    public function collectList(int $page = 1, int $pageSize = 10): void
    {
        $collectModel = new \app\admin\model\Collect();
        $list = $collectModel->with('product')->where('user_id', $this->auth->id)->order('create_time desc')->page($page, $pageSize)->select()->toArray();
        $this->success('获取成功', $list, 1, 'json');
    }
    /**
     * 获取足迹的列表 加 分页
     * throws Throwable
     */
    public function footprintList(int $page = 1, int $pageSize = 10): void
    {
        $footprintModel = new \app\admin\model\Footprint();
        $list = $footprintModel->with('product')->where('user_id', $this->auth->id)->order('create_time desc')->page($page, $pageSize)->select()->toArray();
        $this->success('获取成功', $list, 1, 'json');
    }
    /**
     * 获取积分记录列表
     */
    public function scorelog(int $page = 1, int $pageSize = 10,int $typeid = 0): void
    {
        $pointsLogModel = new \app\admin\model\UserScoreLog();
        $where = [];
        if($typeid==1){
            $where[] = ['score','>',0];
        }
        if($typeid==2){
            $where[] = ['score','<',0];
        }
        if ($typeid == 3) {
            //1年前的积分记录
            $time = time() - 365 * 24 * 3600;
            $where[] = ['create_time', '<', $time];
        }

        $list = $pointsLogModel->where('user_id', $this->auth->id)->where($where)->order('create_time desc')->page($page, $pageSize)->select()->toArray();
        foreach($list as &$item){
            $item['create_time'] = date('Y-m-d',$item['create_time']);
            if($item['score']>0){
                $item['score'] = '+'.$item['score'];
            }
        }
        $this->success('获取成功', $list, 1, 'json');
    }
    /**
     * 新增收货地址
     * @throws Throwable
     */
    public function addAddress(): void
    {
        if ($this->request->isPost()) {
            $params = $this->request->post(['name', 'mobile', 'city', 'info', 'remark', 'default']);
            if (!$params['name'] || !$params['mobile'] || !$params['city'] || !$params['info']) {
                $this->error('参数错误');
            }
            $addressModel = new \app\admin\model\Address();
            $addressModel->create([
                'user_id' => $this->auth->id,
                'name' => $params['name'],
                'phone' => $params['mobile'],
                'info' => $params['info'],
                'city' => $params['city'],
                'remark' => $params['remark'],
                'create_time' => time(),
                'default' => $params['default']
            ]);
            //如果设置为默认 要把其他的默认去掉
            if ($params['default']) {
                $addressModel->where('user_id', $this->auth->id)->where('id', '<>', $addressModel->id)->update(['default' => 0]);
            }
            $this->success('添加成功');
        }
    }
    /**
     * 编辑收货地址
     * @throws Throwable
     */
    public function editAddress(int $id = 0): void
    {
        if (!$id) {
            $this->error('参数错误');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post(['name', 'mobile', 'city', 'info', 'remark', 'default']);
            if (!$params['name'] || !$params['mobile'] || !$params['city'] || !$params['info']) {
                $this->error('参数错误');
            }
            $addressModel = new \app\admin\model\Address();
            $res = $addressModel->where('id', $id)->where('user_id', $this->auth->id)->update([
                'name' => $params['name'],
                'phone' => $params['mobile'],
                'info' => $params['info'],
                'city' => $params['city'],
                'remark' => $params['remark'],
                'default' => $params['default']
            ]);
            //如果设置为默认 要把其他的默认去掉
            if ($params['default']) {
                $addressModel->where('user_id', $this->auth->id)->where('id', '<>', $id)->update(['default' => 0]);
            }
            if ($res === false) {
                $this->error('编辑失败');
            }
            $this->success('编辑成功');
        }
    }
    /**
     * 获取我的地址列表
     * @throws Throwable
     */
    public function addressList(): void
    {
        $addressModel = new \app\admin\model\Address();
        $list = $addressModel->where('user_id', $this->auth->id)->order('default desc,create_time desc')->select()->toArray();
        $this->success('获取成功', $list, 1, 'json');
    }
    /**
     * 常见问题列表
     * @throws Throwable
     */
    public function faqList(): void
    {
        $faqModel = new \app\admin\model\Question();
        $list = $faqModel->order('weigh desc,id desc')->select()->toArray();
        $this->success('获取成功', $list, 1, 'json');
    }

}